<%@page import="net.chat.server.ChatServer"%>
<%@page import="net.chat.utils.Util"%>
<%@page import="net.chat.User"%>
<%@page import="net.chat.Forum"%>
<%
            String redirectUrl = "";
            User user = null;
            Forum forum = null;
            String forumname = "";
            int uid = 0;
            String username = "";

            // if not user session, redirect to login
            Object user_sess = session.getAttribute(Util.USER_SESS);
            if (user_sess == null) {
                redirectUrl = "login.jsp?err=2";
            } else {
                user = (User) user_sess;
                if (user != null) {
                    uid = user.getUid();
                    username = user.getFname() + " " + user.getLname();
                }
            }
            ChatServer server = ChatServer.getInstance();
            String fid = request.getParameter("fid");
            // if not fid parameter, redirect to forums page with err=f
            if (fid == null) {
                redirectUrl = "forums.jsp?err=f";
            } else {
                // otherwise get forum and add user to it
                forum = server.getForum(new Integer(fid).intValue());
                if (forum != null) {
                    forumname = forum.getName();
                    if (user != null) {
                        forum.join(user);
                    }
                }
            }
            if (redirectUrl != "") {
                response.sendRedirect(redirectUrl);
            }
%>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
    Prabhat, initial page, CSS and W3C validation
    Prabhat, implemented rest of chat page
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
        <title>Net-Chat:<%= forumname%></title>
        <link rel="stylesheet" type="text/css" href="../style/common.css"></link>
        <script type="text/javascript" src="../js/jquery.min.js"></script>
        <script type="text/javascript">

            var rqTimeout = <%= Util.AJAX_LONG_LIVE_TIMEOUT%>; // 5 minutes
            var from_url = "<%= Util.SERVLET_PATH%>MsgServlet?uid=<%= uid%>&fid=<%= fid%>&timeout=" + rqTimeout;
            var to_url = "<%= Util.SERVLET_PATH%>MsgServlet";

            var users_update_url = "<%= Util.SERVLET_PATH%>ForumServlet?action=getUsers&fid=<%= fid%>&timeout=" + rqTimeout + "&uids=";

            // receive(rcv) function to hold connection to server until a new msg
            // is received. When a msg is received, it is displayed and another
            // call to the function is made to listen for new message.
            function jReceive() {
                $.ajax({
                    url: from_url,
                    success: function(data) {
                        if (data == "redirect") window.location = "forums.jsp?err=i";
                        if (data != "timeout") addmessage(data);
                        jReceive();
                    },
                    cache: false,
                    timeout: rqTimeout,
                    error: function() {
                        addmessage("<span class=\"err\">error</span>");
                        setTimeout("jReceive()", 5000); // wait 5 secs and start receiving again
                    }
                });
            }

            // send(snd) function to send msg to the server when user click on
            // Send button. It validates for empty textbox first. Ajax call returns
            // success if msg is successfully sent to the forum, otherwise a 'failed'
            // msg is printed on the page.
            function jSend() {

                if (!$("#message").val()) {
                    alert("Type a message first!");
                    $('#message').focus();
                    return false;
                }

                var mymsg = $("#message").val();
                $.post(to_url, {uid: <%= uid%>, fid: <%= fid%>, msg: mymsg},
                function(data) {
                    if (data != "success") {
                        addmessage("<span class=\"err\">Send failed: " + mymsg + "</span>");
                    }
                });
                $("#message").val("");
                $('#message').focus();
            }

            function addmessage(msg) {
                $("#messages").append("<br/>" + msg);
                $("#messages").scroll();
            }

            var uids = "";
            // function to update the list of users in the forum. It makes a long
            // hold ajax connection and listen for any change to the user list and
            // then updates the div. The response is returned in JSON format.
            function jUpdateUsers() {
                $.ajax({
                    url: users_update_url + uids,
                    success: function(data) {
                        if (data != "timeout") {
                            //Get the AJAX response and run the JavaScript evaluation function
                            //on it to turn it into a usable object.  Notice since we are passing
                            //in the JSON value as a string we need to wrap it in parentheses
                            if (data) {
                                var response = eval("(" + data + ")");
                                var newusers = "";
                                uids = "";
                                for(i=0;i < response.users.user.length; i++) {
                                    newusers += response.users.user[i].fname + "<br/>";
                                    uids += response.users.user[i].id + ",";
                                }
                                document.getElementById("users").innerHTML = newusers; // $("#users").html(newusers);
                                if (uids != "") uids = uids.substring(0, uids.length - 1); // remove last comma
                            }
                        }
                        jUpdateUsers();
                    },
                    cache: false,
                    timeout: rqTimeout,
                    error: function() {
                        setTimeout("jUpdateUsers()", 5000); // wait 5 secs and start receiving again
                    }
                });
            }

            $(document).ready(function() {
                jReceive();
                jUpdateUsers();
                $("#send").click(function () {
                    jSend();
                });
            });

        </script>
    </head>
    <body>
        <div id="container">
            <div id="top">
                <h1>Net-Chat</h1>
            </div>
            <div id="leftnav">
                <p>
                    <%
                                out.print("<b>Hello " + username + "!</b>");
                                out.print(" <a href=\"" + Util.SERVLET_PATH + "UserServlet?action=logout&uid=" + uid + "\">logout</a>");
                    %>
                    <br /><br />
                    This is an example of an active forum with users and messages being sent/received instantaneously.
                </p>
            </div>
            <div id="content">
                <h2>Forum: <%= forumname%></h2>
                <p>
                    <a href="<%= Util.SERVLET_PATH%>ForumServlet?action=leave&uid=<%= uid%>&fid=<%= fid%>">leave forum</a> (automatic after 30 mins of inactivity)
                </p>
                <p>
                    <textarea name="message" id="message" class="chatmsg" rows="" cols=""></textarea>
                    <input type="button" id="send" value="send" class="sendmsg" />
                </p>

                <div id="messages" class="chatwindow"></div>
                <div class="chatusers">
                    <strong>Active users:</strong><br/>
                    <div id="users"></div>
                </div>
            </div>
            <div id="footer">
                <div class="alignleft">Author: Totoo</div>
                <div class="alignright">Network Applications</div>
                <div class="clr"></div>
            </div>
        </div>
        <p class="center">
            <a href="http://validator.w3.org/check?uri=referer">
                <img class="w3img" src="../img/valid-xhtml10-blue.png" alt="Valid XHTML 1.0 Strict" />
            </a>
            <a href="http://jigsaw.w3.org/css-validator/check/referer">
                <img class="w3img" src="../img/vcss-blue.gif" alt="Valid CSS!" />
            </a>
        </p>
    </body>
</html>